<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var smallestNumber = function (pattern) {
      pattern += 'I';
      const stack = [];
      let res = '';
      for (let i = 1; i <= pattern.length; i++) {
        if (pattern[i - 1] === 'I') {
          res += i;
          while (stack.length) {
            res += stack.pop();
          }
        } else {
          stack.push(i);
        }
      }
      return res;
    };
    console.log(smallestNumber("IIIDIDDD"));
  </script>
</body>

</html>